package com.jcli.jb51_net.article._232524碰撞小球;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 按钮防抖
 * @author li
 */
public class DebouncedJButton extends JButton {
    private final AtomicBoolean isDebouncing = new AtomicBoolean(true);
    /**
     * 防抖时间，比如500毫秒
     */
    private final int debounceTime;
  
    public DebouncedJButton(String text, int debounceTime) {  
        super(text);  
        this.debounceTime = debounceTime;  
        addActionListener(new ActionListener() {
            @Override  
            public void actionPerformed(ActionEvent e) {
                if (isDebouncing.get()) {  
                    return;  
                }  
                isDebouncing.set(true);  
                try {  
                    // 执行你的逻辑  
                } finally {  
                    isDebouncing.set(false);  
                }  
            }  
        });  
    }  
  
    @Override  
    public void setEnabled(boolean enabled) {  
        super.setEnabled(enabled);  
        if (!enabled) {  
            isDebouncing.set(true); // 当按钮不可用时，确保不触发防抖机制  
        }  
    }  
}